package com.traffic.api.restful;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONObject;
import com.google.gson.Gson;
import com.gxhl.api.core.model.GDPResponse;
import com.gxhl.api.core.tools.JerseyClient;
import com.sun.jersey.api.client.ClientResponse;
import com.traffic.api.config.ApiProperties;
import com.traffic.api.exception.ApiBizException;
import com.traffic.api.jedis.JedisClient;
import com.traffic.managent.model.system.Customer;
import com.traffic.managent.model.system.User;

@Path("/{v}/customer")
public class CustomerRestful extends CheckRestful {
	private static final String HOST_PATH = ApiProperties.FLOW_HOST + "rest/1.0/customer";
	private static Logger LOG = Logger.getLogger(CustomerRestful.class);
	static JedisClient client = JedisClient.getInstance();

	@POST
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public GDPResponse getCustomer(JSONObject param, @PathParam("v") String v) {
		GDPResponse result = new GDPResponse();
		try {
			@SuppressWarnings("unused")
			Map<String, Object> params = check(param,"status");
			ClientResponse response = JerseyClient.getInstance().post(HOST_PATH, param);

			if (response.getStatus() == 500) {
				result.setCode("0001");
				result.setMsg("查询客户信息异常 ：");
			} else if (response.getStatus() != 200) {
				result.setCode("0001");
				result.setMsg("查询客户信息异常 ");
			} else if (response.getStatus() == 200) {
				result.setCode("0000");
				GDPResponse output = (GDPResponse) response.getEntity(GDPResponse.class);
				result.setMsg(output.getMsg());
				result.setData(output.getData());
			}
		} catch (ApiBizException e) {
			result.setCode("0001");
			result.setMsg(e.getCause().getMessage());
		} catch (WebApplicationException e) {
			result.setCode("0001");
			result.setMsg(e.getCause().getMessage());
		} catch (Exception e) {
			result.setCode("0001");
			result.setMsg("系统异常");
			e.printStackTrace();
		}

		return result;
	}
	
	
	/**
	 * 点博专用
	 * @param formParams
	 * @return
	 */
	@POST
	@Consumes({"application/x-www-form-urlencoded"})  
	@Produces({"text/plain;charset=gbk"})
	@Path("/db/getCustomer")
	public String getCustomer(MultivaluedMap<String, String> formParams,@PathParam("v") String v) {
		LOG.info("api- rest/1.0/customer/getCustomer 请求参数： :" + formParams);
		StringBuilder resultStringBuilder = new StringBuilder();
		String INTECMD = formParams.getFirst("INTECMD");
		String CTMID = formParams.getFirst("CTMID");//商户编号
		String result = "";
		if (!"YECX".equals(INTECMD)) {//接口命令字
			result = resultStringBuilder.append("STATUS=106").append("&CTMID="+CTMID).toString();
			return result;
		}
		
		try {
			JSONObject param = new JSONObject();
			param.put("appkey", ApiProperties.DIANBO_CTMID);//商户ID
			checkParam(param,"customer");
			Map usermap = new HashMap();
			String jsonuser = client.get("user_json" + ApiProperties.DIANBO_CTMID);
			User user = new Gson().fromJson(jsonuser, User.class);
			usermap = user.getAttrs();
			String customerId = (String) usermap.get("customerid");
			Map<String,Object> customermap = new HashMap<String,Object>();
			String jsoncustomer = client.get("customer_json" + customerId);
			Customer customer = new Gson().fromJson(jsoncustomer, Customer.class);
			customermap = customer.getAttrs();
			String CTMACCRES = customermap.get("amount").toString()+"00";


			String waitSign ="CTMACCRES="+CTMACCRES+"&CTMID="+CTMID+"&STATUS=1"+ApiProperties.DIANBO_KEY;
			String sign = getMD5(waitSign);
			result = resultStringBuilder.append("SIGN="+sign).append("&STATUS=1").append("&CTMID="+CTMID).append("&CTMACCRES="+CTMACCRES).toString();
	
		}catch (ApiBizException e){
			LOG.error("getCustomer[" + formParams + "],error :",e);
			if (e.getCause().getMessage().contains("(api)您的ip未绑定")) {
				String waitSign ="CTMID="+CTMID+"&STATUS=111"+ApiProperties.DIANBO_KEY;
				String sign = getMD5(waitSign);
				result = resultStringBuilder.append("STATUS=111").append("&CTMID="+CTMID).append("&SIGN="+sign).toString();
			}else {
				result = resultStringBuilder.append("STATUS=109").append("&CTMID="+CTMID).toString();
			}
		} catch (Exception e) {
			LOG.error("getCustomer[" + formParams + "],error :", e);
			String waitSign ="CTMID="+CTMID+"&STATUS=0"+ApiProperties.DIANBO_KEY;
			String sign = getMD5(waitSign);
			result =resultStringBuilder.append("STATUS=0").append("&CTMID="+CTMID).append("&SIGN="+sign).toString();
		}
		LOG.info("getCustomer 返回的信息："+result);
		return result;
	}
		
		public static String getMD5(String message) {
		
			MessageDigest messageDigest = null;
			StringBuffer md5StrBuff = new StringBuffer();
			try {
				messageDigest = MessageDigest.getInstance("MD5");
				messageDigest.reset();
				messageDigest.update(message.getBytes("GBK"));

				byte[] byteArray = messageDigest.digest();
				for (int i = 0; i < byteArray.length; i++) {
					if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
						md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
					else
						md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
				}
			} catch (Exception e) {
				throw new RuntimeException();
			}
			
			return md5StrBuff.toString().toLowerCase();// 字母小写
		}
}